# %%
# import sys
# sys.path.append("..")
# codeing= utf-8
from DataTools import dayTimes as TT
from DataTools import tsData as tsData
import pandas as pd
from pathlib import Path

"""
+ 文件说明
+ getNmaeList(): 通过TS列表获取股票代码与相关信息
+ SercherCode(): 通过TS文件搜索指定股票所有信息
+ SerchbyTime():某个窗口期中所有上市股票
+ getReports():获取163股票历史数据
+ TimeRange():获取所有交易时间
+ getDateList():获取之前文件中开始时间和表格，返回 时间，表格
+ ProcessTImeList(): 差值化处理时间
+ GetRangeK(): df.Groupby封装，对数据进行压缩处理
+ getCodeandTime(): 输出字典格式，{code：[时间，区域]}
+ fileChack(): #
"""



def TimeRange(year):
    """
    + 获取一年中的交易日数据
    year 年单位， 周可以输入 x/52 月 x/12
    """

    if Path(r"tables/basic/trade_days.csv").is_file():
        l = tsData.getTradeDays(methods="1")
    else:
        l = tsData.getTradeDays(methods="get")
    if year > 20:
        return l
    start, today = TT.getYear(year)
    startime = int("".join(start.split("-")))
    todaytime = int("".join(today.split("-")))

    for i in range(14):
        if startime in l and todaytime in l:
            si = l.index(startime)
            st = l.index(todaytime)
            l = l[si : st + 1]
            # print(l)
            return l

        elif startime not in l:
            if int(str(start)[-2:]) > 31:
                startime += 70
            else:
                startime = int(startime) + 1
            # print("start", startime)

        elif todaytime not in l:
            todaytime = int(todaytime) - 1
            # print(todaytime, "end")
            # return [today]
    print("格式错误 -- 无法找到有效时间")


# %%
def getDateList(code, Fpath, colName="time"):
    """
    检索之前文件，填补交易日中的空缺时间
    """
    Fpath = Fpath + (code) + ".csv"
    if Path(Fpath).is_file():
        old = pd.read_csv(Fpath, index_col=None)
        datetype = old.loc[0, colName]
        if len(datetype) > 10 and isinstance(datetype, str):
            last_time = old[colName].apply(lambda x: x.split(" ")[0])
        else:
            last_time = old[colName]

        _d = pd.DataFrame()
        if len(last_time.iloc[0].split("-")) > 0:
            _d = last_time.str.split("-", expand=True)
            _d.columns = ["y", "m", "d"]

        else:
            _d = last_time.str.split("/", expand=True)
            _d.columns = ["y", "m", "d"]

        # print(last_time.iloc[1], _d.iloc[1])
        last_time = _d.loc[:, "y"] + _d.loc[:, "m"] + _d.loc[:, "d"]
        last_time = set(last_time.tolist())
        last_time = [int(i) for i in last_time]
        last_time.sort()
        # print(old.head(-3))
        return last_time, old
    else:
        return None, None


# %%


def ProcessTimeList(starttime, newTimelist, last_time):
    """
    时间列表检测
    返回值位列表
    starttime = 开始时间
    newTimelist = 时间列表
    last = 终止时间
    :: return: TimeList
    """
    if starttime != None and newTimelist != None:
        if starttime in newTimelist:
            newTimelist = newTimelist[newTimelist.index(starttime) :]

        if last_time != None:
            newTimelist = list(set(newTimelist).difference(set(last_time)))
            newTimelist.sort()

        if newTimelist != []:
            if newTimelist[0] < starttime:
                for i in range(14):
                    starttime -= 1
                    if starttime in newTimelist:
                        newTimelist = newTimelist[newTimelist.index(starttime) :]
            return newTimelist
    else:
        return None


# %%
# def fileChack(Fp):
#     """
#     Fp=filePath
#     检查文件是否存在，存在打开，不存在返回两个空值
#     正常返回 df，starttime
#     """
#     if Path(Fp).is_file():
#         df = pd.read_csv(Fp)
#         start = ''.join(df['date'].iloc[-1].split('-'))
#         return df, start
#     else:
#         return None, None
# %%

# def getK_states(info, types="ts"):
#     """
#     + 获取历史数据163
#     + 反馈url
#     + getK_states(SercherCode(inputstr="600009", types="ts))
#     """
#     if types == "163":
#         # 获取历史数据 163
#         if len(info["ts_code"].tolist()) == 1:
#             codeinfo = info["ts_code"].iloc[0].split(".")
#             last_date = info["list_date"].iloc[-1]
#             if codeinfo[1] == "SZ":
#                 area = 1
#             else:
#                 area = 0
#             url = "http://quotes.money.163.com/service/chddata.html?code={}{}&start={}&end={}&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP".format(
#                 area, codeinfo[0], last_date, TT.getodays(forward=1)[2])
#             return url
#         else:
#             print(info)
#             print("结果过多或没有检索到结果")


# getK_states(SercherCode(inputstr="600009", module=0))
